<!--suppress HtmlDeprecatedAttribute -->
<template>
  <app-main-wrapper :loading="loading">
    <page-title class="title" title='ORDER' subtitle='ORDER'
                :style='{background: "url(" + titleBackImg + ")"}'/>
    <div class="main-content" style="text-align: left">
      <address-manager-dialog v-model="dialogVisible" :id="dialogAddrId" @change="addressChange"/>
      <div class="step">
        <el-steps :active="1" align-center>
          <el-step title="拍下商品" icon="el-icon-edit"/>
          <el-step title="付款到支付宝" icon="el-icon-upload"/>
          <el-step title="确定收货" icon="el-icon-present"/>
          <el-step title="评价" icon="el-icon-star-on"/>
        </el-steps>
      </div>
      <span class="sbuTitle">选择收货地址</span>
      <div class="address">
        <el-row :gutter="20">
          <template v-for="(item, index) in addressList">
            <el-col :span="6" :key="index" v-if="showAllAddr || index < 4">
              <div style="width: 100%; height: 110px; overflow: hidden">
                <address-item class="address-item" @click="handleClickAddress" @default="handleClickAddrDefault"
                              @change="handleClickAddrChange" :address="item" :change-loading="dialogVisible"
                              :change-text="dialogVisible ? '打开中' : '修改地址'" :change-disabled="dialogVisible"
                              :active="activeAddressId === item.id"/>
              </div>
            </el-col>
          </template>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="12" align="left">
            <el-button v-if="addressList.length > 4" type="text" @click="handleShowAllAddr">
              {{showAllAddr ? '显示部分地址' : '显示全部地址'}}
            </el-button>
          </el-col>
          <el-col :span="12" align="right">
            <el-button type="text" @click="handleAddAddr" :loading="dialogVisible">新增地址</el-button>
          </el-col>
        </el-row>
      </div>
      <span class="sbuTitle">确认订单信息</span>
      <div class="goods">
        <el-table :data="goods" style="width: 100%">
          <el-table-column prop="good" label="店铺宝贝" width="400" align="left">
            <template slot-scope="scope">
              <good-box-simple v-bind="scope.row"/>
            </template>
          </el-table-column>
          <el-table-column prop="subGoodName" label="商品属性" width="180" align="center">
          </el-table-column>
          <el-table-column prop="price" label="单价" align="center">
          </el-table-column>
          <el-table-column prop="count" label="数量" width="220" align="center">
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.orderCount" :min="1" :max="100"/>
            </template>
          </el-table-column>
          <el-table-column prop="address" label="优惠方式" align="center">
            无
          </el-table-column>
          <el-table-column prop="allPrice" label="小计" align="center">
              <span style="font-size: 20px; font-weight: 600; color: red;">
                {{'￥' + allGoodPrice}}
              </span>
          </el-table-column>
        </el-table>
        <el-form label-width="120px" style="margin-top: 16px;">
          <el-row :gutter="10">
            <el-col :span="12">
              <el-form-item label="给买家留言">
                <el-input type="textarea" placeholder="选填，请先跟商家协调一致" v-model="message"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-row :gutter="10">
                <el-col :span="15">
                  <el-form-item label="运送方式">
                    {{trueFreight > 0 ? '快递' : '包邮'}}
                  </el-form-item>
                </el-col>
                <el-col :span="7" style="">
                  <el-form-item label="">
                    <span style="font-size: 16px; font-weight: 600; color: red; margin-top:12px;">
                    {{trueFreight > 0 ? '￥' + trueFreight : '￥0.00'}}
                    </span>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div class="submitWrap">
        <div class="submit">
          <div class="wrap">
            <span class="submitTitle">实付款：</span>
            <span class="price">{{'￥' + allPrice}}</span>
          </div>
          <div class="wrap">
            <span class="submitTitle">寄送至：</span>
            <span class="content">{{addressDesc}}</span>
          </div>
          <div class="wrap">
            <span class="submitTitle">收货人：</span>
            <span class="content">{{addressPeople}}</span>
          </div>
          <div class="wrap">
            <el-button type="primary" class="btn" :disabled="submitLoading"
                       @click="submitOrder">提交订单
            </el-button>
          </div>
        </div>
      </div>
    </div>
  </app-main-wrapper>
</template>

<script>
import AppMainWrapper from '@/components/wrapper/AppMainWrapper'
import PageTitle from '@/views/part/index/PageTitle'
import titleImg from '@img/page-titlebg.png'
import AddressItem from '@/views/part/toOrder/AddressItem'
import { queryAllUserAddress } from '@/api/ApiUserAddress'
import { ResultCode } from '@/constants/constants'
import AddressManagerDialog from '@/views/part/toOrder/AddressManagerDialog'
import GoodBoxSimple from '@/components/general/goods/GoodBoxSimple'
import { queryGoodDetailById } from '@/api/ApiGoodDetail'
import { convertDetailToOrderItem } from '@/utils/DataConvertUtils'
import GoodOrderInsertDTO from '@/api/entity/GoodOrderInsertDTO'
import { insertGoodOrderDTO, payOrderById } from '@/api/ApiOrderDetail'
import { MessageBox } from 'element-ui'

// noinspection JSUnusedGlobalSymbols
export default {
  name: 'AppToOrder',
  props: {
    goodId: {
      required: true,
      type: [Number, String]
    },
    subGoodId: {
      required: true,
      type: [Number, String]
    },
    count: {
      required: true,
      type: [Number, String]
    }
  },
  components: {
    GoodBoxSimple,
    AddressManagerDialog,
    AddressItem,
    PageTitle,
    AppMainWrapper
  },
  data () {
    return {
      addrLoading: true,
      submitLoading: false,
      goodLoading: true,
      titleBackImg: titleImg,
      addressList: [],
      activeAddressId: 0,
      activeAddress: null,
      showAllAddr: false,
      dialogVisible: false,
      dialogAddrId: 0,
      good: {},
      // 留言
      message: ''
    }
  },
  computed: {
    loading () {
      return this.addrLoading || this.goodLoading
    },
    goods () {
      return [this.good]
    },
    allGoodPrice () {
      return this.good.orderCount * this.good.price
    },
    trueFreight () {
      return this.good && this.good['freight'] && this.good['freight'] > 0 ? this.good['freight'] : 0
    },
    allPrice () {
      return this.allGoodPrice + this.trueFreight
    },
    addressDesc () {
      if (!this.activeAddressId || this.activeAddressId <= 0 || !this.activeAddress) {
        return '未选择地址'
      }
      let desc = ''
      if (this.activeAddress['provinceName']) {
        desc += this.activeAddress['provinceName']
        desc += ' '
      }
      if (this.activeAddress['cityName']) {
        desc += this.activeAddress['cityName']
        desc += ' '
      }
      if (this.activeAddress['countyName']) {
        desc += this.activeAddress['countyName']
        desc += ' '
      }
      if (this.activeAddress['detail']) {
        desc += this.activeAddress['detail']
        desc += ' '
      }
      return desc
    },
    addressPeople () {
      if (!this.activeAddressId || this.activeAddressId <= 0 || !this.activeAddress) {
        return '未选择地址'
      }
      let desc = ''
      if (this.activeAddress['username']) {
        desc += this.activeAddress['username']
        desc += ' '
      }
      if (this.activeAddress['phone']) {
        desc += this.activeAddress['phone']
        desc += ' '
      }
      return desc
    }
  },
  methods: {
    freshAddressData () {
      this.addrLoading = true
      queryAllUserAddress(data => {
        if (data && data.code === ResultCode.OK) {
          this.addressList = data.object
        }
      }, () => {
        this.addrLoading = false
      })
    },
    freshGoodDetailData () {
      this.goodLoading = true
      queryGoodDetailById(this.goodId, data => {
        if (data && data.code === ResultCode.OK) {
          const good = convertDetailToOrderItem(data.object, this.subGoodId)
          good.orderCount = this.count
          this.good = good
        }
      }, () => {
        this.goodLoading = false
      })
    },
    initData () {
      this.freshAddressData()
      this.freshGoodDetailData()
    },
    /**
       * 点击地址,选中
       */
    handleClickAddress (item) {
      if (this.activeAddressId !== item.id) {
        this.activeAddressId = item.id
        this.activeAddress = item
      } else {
        this.activeAddressId = 0
        this.activeAddress = null
      }
    },
    /**
       * 设置为默认地址,选中
       */
    handleClickAddrDefault (item) {

    },
    /**
       * 修改收货地址
       */
    handleClickAddrChange (item) {
      this.dialogAddrId = item.id
      this.dialogVisible = true
    },
    /**
       * 新增收货地址
       */
    handleAddAddr () {
      this.dialogAddrId = 0
      this.dialogVisible = true
    },
    /**
       * 显示全部收货地址
       */
    handleShowAllAddr () {
      this.showAllAddr = !this.showAllAddr
    },
    /**
     * 地址改变
     */
    addressChange () {
      this.freshAddressData()
    },
    /**
       * 提交订单
       */
    submitOrder () {
      const dto = GoodOrderInsertDTO.instance()
      if (!this.subGoodId || this.subGoodId <= 0) {
        this.$message.error('错误的商品id')
        return
      }
      if (!this.activeAddressId || this.activeAddressId <= 0) {
        this.$message.error('请先选择收货地址')
        return
      }
      if (!this.good.orderCount || this.good.orderCount <= 0) {
        this.$message.error('商品数量必须大于零')
        return
      }
      dto.setSubGoodId(this.subGoodId)
      dto.setAddressId(this.activeAddressId)
      dto.setCount(this.good.orderCount)
      dto.setMessage(this.message)
      this.submitLoading = true
      insertGoodOrderDTO(dto, data => {
        if (data && data.code === ResultCode.OK) {
          this.$message.success('提交订单成功')
          MessageBox.alert('提交订单成功，是否前往支付？', '提交成功', {
            confirmButtonText: '确定',
            showCancelButton: true,
            cancelButtonText: '取消',
            type: 'success',
            callback: (flag) => {
              if (flag === 'confirm') {
                // 前往付款
                payOrderById(data['object'].id)
              }
            }
          })
        }
      }, () => {
        this.submitLoading = false
      })
    }
  },
  // 滚动到最上面
  mounted () {
    this.initData()
  }
}
</script>

<style lang="scss" scoped>

  .title {
    width: 100%;
    height: 180px;
    user-select: none;
    padding: 54px 220px;
    letter-spacing: -1px;
  }

  .main-content {
    max-width: 1110px;
    width: 100%;
    margin: 0 auto;

    .sbuTitle {
      display: block;
      margin: 10px;
      font-size: 16px;
      font-weight: 600;
    }

    .step {
      margin: 40px 30px;
    }

    .address {

      margin-top: 10px;
      margin-bottom: 20px;

      .address-item {
      }

    }

    .submitWrap {
      width: 100%;
      height: 154px;
      margin-bottom: 16px;
    }

    .submit {
      height: 100%;
      width: 60%;
      border: 2px solid red;
      text-align: right;
      float: right;
      padding-right: 16px;

      .wrap {
        margin: 6px 0;
      }

      .submitTitle {
        font-weight: 700;
        color: #333;
      }

      .price {
        font: 700 26px tahoma;
        color: rgb(255, 0, 54)
      }

      .content {
        font-family: verdana, -apple-system, BlinkMacSystemFont, Helvetica Neue, Helvetica, Tahoma, PingFang SC, Hiragino Sans GB, Microsoft YaHei, sans-serif;
        font-size: 14px;
      }

      .btn {
        background: rgb(255, 0, 56);
        border-radius: 0;
        border: 0;
        margin-top: 4px;
      }

    }

  }

</style>
